package patrol.mobile.com.mobilepatrol.activity.toll.add_data;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.imagepicker.bean.ImageItem;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.Item;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.GangweiKaoheBean;
import patrol.mobile.com.mobilepatrol.bean.OrgPostTemplateListBean;
import patrol.mobile.com.mobilepatrol.bean.Parent;
import patrol.mobile.com.mobilepatrol.bean.UpImgInfoBean;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.utils.Constants;
import patrol.mobile.com.mobilepatrol.utils.LuBanHelper;
import patrol.mobile.com.mobilepatrol.utils.SPUtils;
import patrol.mobile.com.mobilepatrol.utils.ToastUtils;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack;
import patrol.mobile.com.mobilepatrol.utils.net.HttpSender;

/**
 * 测试
 */
public class AddDataPage2Activity extends BaseActivity {
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.tv2)
    TextView tv2;
    @BindView(R.id.tv3)
    TextView tv3;
    @BindView(R.id.myRecyclerView)
    RecyclerView myRecyclerView;
    private GangweiKaoheBean gangweiKaoheBean;
    private OrgPostTemplateListBean orgPostTemplateListBean;
    private MyAdapter myAdapter;

    private List<String> imgUUIDs = new ArrayList<>();
    ArrayList<ImageItem> selImageList;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_add_data_page2_layout;
    }

    @Override
    public void initView() {
        super.initView();
        selImageList = new ArrayList<>();
        gangweiKaoheBean = (GangweiKaoheBean) getIntent().getSerializableExtra("data");
        tv1.setText("被考核人：" + gangweiKaoheBean.getBeikaoheren());
        tv2.setText("考核人：" + gangweiKaoheBean.getKaoheren());
        tv3.setText("总扣分：0");
        myRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        getHttpData();
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tv_right_title.setVisibility(View.VISIBLE);
        tv_right_title.setText("保存");
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("考核明细");
        tv_right_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                commitData();
            }
        });
    }

    /**
     * 提交记录
     */
    private void commitData() {
        HashMap<String, String> hashMap = new HashMap();
        orgPostTemplateListBean.setId(System.currentTimeMillis() + UserManager.getUserId());
        orgPostTemplateListBean.setMouthDate(gangweiKaoheBean.getShijain());
        //得分
        int totalScore = 0;
        //扣分
        int score = 0;
        for (OrgPostTemplateListBean.ListBean listBean : orgPostTemplateListBean.getList()) {
            totalScore = totalScore + listBean.getTotalScore();
            score = score + listBean.getItemScore();
        }
        orgPostTemplateListBean.setTotalScore(totalScore);
        orgPostTemplateListBean.setDeductScore(score);
        orgPostTemplateListBean.setAssessmentPost(gangweiKaoheBean.getKaohegangwei());
        //被考察人ID
        HashMap<String, String> checkNameId = new HashMap<>();
        checkNameId.put("id", gangweiKaoheBean.getBeikaoherenId());
        orgPostTemplateListBean.setCheckNameId(checkNameId);
        orgPostTemplateListBean.setCheckName(gangweiKaoheBean.getBeikaoheren());
        //当前单位
        HashMap<String, String> org = new HashMap<>();
        org.put("id", UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).bmcode);
        org.put("orgName", gangweiKaoheBean.getDanwei());
        orgPostTemplateListBean.setOrg(org);
        orgPostTemplateListBean.setOrgId(UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).bmcode);
        orgPostTemplateListBean.setOrgName(gangweiKaoheBean.getDanwei());
        orgPostTemplateListBean.setAssessor(gangweiKaoheBean.getKaoheren());
        orgPostTemplateListBean.setPeriod(gangweiKaoheBean.getDangqianbanci());
        orgPostTemplateListBean.setAuditFlag("1");
        orgPostTemplateListBean.setAuditName("申诉中");
//        orgPostTemplateListBean.setOrgPostItemList(orgPostTemplateListBean.getList());

        //图片上传
        selImageList.clear();
        List<UpImgInfoBean> upImgInfoBeanList = new ArrayList<>();
        for (OrgPostTemplateListBean.ListBean listBean : orgPostTemplateListBean.getList()) {
            listBean.setIsNewRecord(true);
            if (null != listBean.getSelImageList()) {
                for (ImageItem image : listBean.getSelImageList()) {
                    UpImgInfoBean imgInfoBean = new UpImgInfoBean();
                    imgInfoBean.setBusniessId(listBean.getId());
                    imgInfoBean.setContentType("orgPostItem");
                    imgInfoBean.setFileType("img");
                    String uuid = UUID.randomUUID().toString();
                    imgUUIDs.add(uuid);
                    imgInfoBean.setId(uuid);
                    upImgInfoBeanList.add(imgInfoBean);
                }
                selImageList.addAll(listBean.getSelImageList());
            }
        }
//        .replace("list", "orgPostItemList")
        hashMap.put("mainJson", new Gson().toJson(orgPostTemplateListBean).replace("list", "orgPostItemList"));
        HttpSender sender = new HttpSender(this, baseUrl, Urls.orgPostUploadData);
        sender.requestPost(hashMap, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                upImag();
            }
        });
    }


    @Override
    public void setListener() {

    }

    private void getHttpData() {
        HashMap<String, String> hashMap = new HashMap();
        hashMap.put("post", gangweiKaoheBean.getKaohegangwei());
        hashMap.put("department", gangweiKaoheBean.getDanwei());
        HttpSender sender = new HttpSender(this, baseUrl, Urls.GET_ORG_POST_TEMPLATE_LIST);
        sender.requestPost(hashMap, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                orgPostTemplateListBean = new Gson().fromJson(response, OrgPostTemplateListBean.class);
                if (null == orgPostTemplateListBean.getList()) {
                    ToastUtils.showToast("输入内容错误");
                    finish();
                }
                manageData(orgPostTemplateListBean);
                myRecyclerView.setAdapter(myAdapter = new MyAdapter());
            }
        });
    }

    private void manageData(OrgPostTemplateListBean orgPostTemplateListBean) {
        List<OrgPostTemplateListBean.ParentBean> parentBeanList = new ArrayList<>();
        int i = 0;
        int j = 0;
        OrgPostTemplateListBean.ParentBean parentBean;
        List<OrgPostTemplateListBean.ListBean> listBeanList;
//        for (int k = 0; k < orgPostTemplateListBean.getList().size(); k++) {
//            for (int m = 1; m < orgPostTemplateListBean.getList().size(); m++)
//                if (!orgPostTemplateListBean.getList().get(k).getProLarge().equals(orgPostTemplateListBean.getList().get(m).getProLarge()))
//
//        }
        for (; i < orgPostTemplateListBean.getList().size(); i++) {
//            if (i == 0) {
            parentBean = new OrgPostTemplateListBean.ParentBean();
            listBeanList = new ArrayList<>();
            parentBean.setProLarge(orgPostTemplateListBean.getList().get(i).getProLarge().trim());
            listBeanList.add(orgPostTemplateListBean.getList().get(i));
            j = i + 1;
//            } else {
//                if (j <= orgPostTemplateListBean.getList().size()) {
//
//                    parentBean = new OrgPostTemplateListBean.ParentBean();
//                    listBeanList = new ArrayList<>();
//                    parentBean.setProLarge(orgPostTemplateListBean.getList().get(j).getProLarge());
//                    listBeanList.add(orgPostTemplateListBean.getList().get(j));
//                }else{
//                    break;
//                }
//            }
            for (; j < orgPostTemplateListBean.getList().size(); j++) {
                if (orgPostTemplateListBean.getList().get(i).getProLarge().trim().equals(orgPostTemplateListBean.getList().get(j).getProLarge().trim())) {
                    listBeanList.add(orgPostTemplateListBean.getList().get(j));
                } else {
                    i = j - 1;
                    break;
                }
            }
            parentBean.setChildList(listBeanList);
            parentBeanList.add(parentBean);
            continue;

        }
        orgPostTemplateListBean.setParentBeanList(parentBeanList);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == Activity.RESULT_CANCELED) {
            orgPostTemplateListBean = (OrgPostTemplateListBean) data.getSerializableExtra("data");
            manageData(orgPostTemplateListBean);
            int score = 0;
            for (OrgPostTemplateListBean.ListBean listBean : orgPostTemplateListBean.getList()) {
                score += listBean.getAccount();
            }
            tv3.setText(score+"");
            myAdapter.notifyDataSetChanged();
        }
    }

    public class MyChildAdapter extends RecyclerView.Adapter<MyChildAdapter.ViewHolder> {
        OrgPostTemplateListBean.ParentBean parentBean;
        Item item;

        public MyChildAdapter(OrgPostTemplateListBean.ParentBean parent, Item item) {
            this.parentBean = parent;
            this.item = item;
        }

        @Override
        public MyChildAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_evaluation_detail_child, parent, false);
            return new MyChildAdapter.ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyChildAdapter.ViewHolder holder, int position) {
            holder.tv_left.setText("余" + parentBean.getChildList().get(position).getItemScore());
            holder.tv_remove.setText("扣" + parentBean.getChildList().get(position).getAccount());
            holder.tv_text.setText(parentBean.getChildList().get(position).getProContent());
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivityForResult(new Intent(AddDataPage2Activity.this, AddDataPage3Activity.class)
                                    .putExtra("data", orgPostTemplateListBean)
                                    .putExtra("position", item.getParentPosition(position))
                            , Activity.RESULT_CANCELED);
                }
            });
        }

        @Override
        public int getItemCount() {
            return parentBean.getChildList().size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.tv_kou)
            TextView tv_left;
            @BindView(R.id.tv_yu)
            TextView tv_remove;
            @BindView(R.id.tv_title_child)
            TextView tv_text;

            ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }
        }
    }

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_evaluation_detail, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, final int position) {
            holder.tvNum.setText(position + 1 + "");
            holder.tvTitle.setText(orgPostTemplateListBean.getParentBeanList().get(position).getProLarge());
            OrgPostTemplateListBean.ParentBean parentBean =orgPostTemplateListBean.getParentBeanList().get(position);
            MyChildAdapter myChildAdapter = new MyChildAdapter(parentBean, new Item() {
                @Override
                public int getParentPosition(int p) {
                    int pos=orgPostTemplateListBean.getList().indexOf(parentBean.getChildList().get(p));


                    return pos;
                }
            });
            holder.rv_child.setAdapter(myChildAdapter);
            holder.rv_child.setLayoutManager(new LinearLayoutManager(holder.rv_child.getContext()));
            holder.re_spand.setVisibility(View.GONE);
            holder.iv_arrow.setImageResource(R.mipmap.arrow_d);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (holder.re_spand.getVisibility() == View.VISIBLE) {
                        holder.re_spand.setVisibility(View.GONE);
                        holder.iv_arrow.setImageResource(R.mipmap.arrow_d);
                    } else {
                        holder.re_spand.setVisibility(View.VISIBLE);
                        holder.iv_arrow.setImageResource(R.mipmap.arrow_u);
                    }
                }
            });
//            holder.rv_child.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
//                @Override
//                public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
//                    return false;
//                }
//
//                @Override
//                public void onTouchEvent(RecyclerView rv, MotionEvent e) {
//
//                }
//
//                @Override
//                public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
//
//                }
//            });
        }

        @Override
        public int getItemCount() {
            return orgPostTemplateListBean.getParentBeanList() == null ? 0 : orgPostTemplateListBean.getParentBeanList().size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.tv_num)
            TextView tvNum;
            @BindView(R.id.tv_title)
            TextView tvTitle;
            @BindView(R.id.tv_yu)
            TextView tvYu;
            @BindView(R.id.tv_kou)
            TextView tvKou;
            @BindView(R.id.re_spand)
            RelativeLayout re_spand;
            //            @BindView(R.id.tv_title_child)
//            TextView tv_text;
//            @BindView(R.id.tv_left)
//            TextView tv_left;
//            @BindView(R.id.tv_remove)
//            TextView tv_remove;
            @BindView(R.id.iv_arrow)
            ImageView iv_arrow;
            @BindView(R.id.rv_child)
            RecyclerView rv_child;

            ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }
        }
    }

    private void upImag() {
        if (selImageList != null && selImageList.size() != 0) {
            List<File> list = new ArrayList<>();
            for (ImageItem imageItem : selImageList) {
                File file = new File(imageItem.path);
                list.add(file);
            }
            List<Map<String, String>> params = new ArrayList<>();
            for (String imgUUID : imgUUIDs) {
                Map<String, String> map = new HashMap<>();
                map.put("id", imgUUID);
                map.put("type", "orgPostItem");
                params.add(map);
            }
            LuBanHelper luBanHelper = new LuBanHelper(AddDataPage2Activity.this, list, params);
            luBanHelper.compression(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                }

                @Override
                public void onResponse(String response, int id) {
                    Toast.makeText(AddDataPage2Activity.this, "提交成功", Toast.LENGTH_SHORT).show();
                    finish();
                }
            });
        } else {
            Toast.makeText(AddDataPage2Activity.this, "提交成功", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

//    public interface Item {
//        int getParentPosition(int position);
//    }
}
